package softtech.apps.autoanswerphonecall;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import softtech.apps.constant.Constant;
import softtech.apps.customadapter.CustomListContactAdapter;
import softtech.apps.customadapter.ItemRecordAdapter;
import softtech.apps.customadapter.ItemSmsAdapter;
import softtech.apps.customadapter.ItemTimingAdapter;
import softtech.apps.customadapter.ItemVoiceRecordAdapter;
import softtech.apps.dropbox.DropboxApi;
import softtech.apps.model.Config;
import softtech.apps.model.Contact;
import softtech.apps.model.DatabaseHandler;
import softtech.apps.model.Message;
import softtech.apps.model.RowRecord;
import softtech.apps.model.RowVoiceRecorded;
import softtech.apps.model.Timer;
import softtech.apps.sync.android.util.RowVoiceRecorderListComparator;
import softtech.apps.sync.android.util.Util;
import softtech.apps.util.IabHelper;
import softtech.apps.util.IabResult;
import softtech.apps.util.Inventory;
import softtech.apps.util.Purchase;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.SearchManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.ContactsContract;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Display;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.widget.ViewFlipper;

import com.android.vending.billing.IInAppBillingService;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.plus.PlusShare;

public class MainActivity extends ActionBarActivity {

	// constant
	public static final int MEDIA_MOUNTED = 0;
	public static final int MEDIA_MOUNTED_READ_ONLY = 1;
	public static final int NO_MEDIA = 2;

	public static final int REQUEST_CODE_DIALOG_ADD_SMS = 0;

	public static final int REQUEST_CODE_DIALOG_EDIT_SMS = 1;

	public static final int REQUEST_CODE_DIALOG_ADD_RECORD = 2;

	public static final int REQUEST_CODE_DIALOG_EDIT_RECORD = 3;

	public static final int REQUEST_LINK_TO_DBX_MAINACTIVITY = 4;

	public static final int REQUEST_CODE_ADD_SCHEDULE = 5;
	
	public static final int REQUEST_CODE_EDT_SCHEDULE = 6;
	
	protected int linkToDropbox;

	public static boolean isSync;
	// In App Billing
	 IabHelper mHelper;
	 //static final String ITEM_SKU = "softtech.apps.autoanswerphonecallprofull";
	static final String ITEM_SKU = "receive_voice_massage";
	static final String ITEM_SKU2 = "softtech.apps.autoanswerphonecallprofull";
	 // receive_voice_massage
	//static final String ITEM_SKU = "android.test.purchased";
	 private static final String TAG = MainActivity.class.getName();
    // Does the user have the premium upgrade?
    SharedPreferences preferences;
    Boolean isPurchased = false;
    static final int RC_REQUEST = 10001;
	// common
	private Context mContext;

	private ActionBar actionBar;

	private PopupMenu popup;

	private int colorActionBarSMS = 0xff223065;

	private Menu mMenu;

	private DatabaseHandler dbHandler;
	
	/**
	 * layout main
	 */
	private ViewFlipper viewFlipper;
	private TextView tvSms, tvRecord, tvListen, tvSetting, tvAbout, tvSchedule;

//	private Button btShareFb, btShareTw, btShareGg;
	TabHost tabs;
	/**
	 * layout answer by sms
	 */
	private ListView lvContent, lvRecord;
	private TextView tvHeaderTitle;
	private TextView tvHeaderContent;
	private int isInitViewAnserBySms = 0;
	private ItemSmsAdapter adapterSms;
	/**
	 * layout answer by record
	 */
	private int isInitViewRecord = 0;
	private ItemRecordAdapter adapterRecord;

	/**
	 * layout answer by listen
	 */
	private ListView lvAllCalls, lvFavorites;

	private List<Contact> listContact;

	private ItemVoiceRecordAdapter adapterAllCalls;

	private int isInitViewListen = 0;
	private int isInitViewSetting = 0;
	private DropboxApi mDropboxApi;
	/**
	 * Layout General setting
	 */
	private boolean mIsCheck = false;
	private int positionTab = 0;
	MenuItem item_search;
	private int isTabContact = 0;
	private Button btGeneralSetting, btSelectContacts, btSyncToDropbox, btLink,
			btUnlink, btRunCleanUp,btBuyFullVersion;
	private ToggleButton btEnableCall, btEnableReceiveVoiceMessage;
	private ToggleButton toggleManual, toggleAuto, toggleEnalbeAskBeforeDel,
			toggleEnalbeAskBeforeDelRR;
	private ViewFlipper mViewFlipper;
	private Config cfgTypeRecord;
	private RadioGroup radGroupTypeRecord, radioGroupTypeReply, mRadioGroup;
	private RadioButton radAllcalls, radContacts, radUnknown, radReplySMS,
			radReplyAudio, radAllCalls, radFavorites;
	private static CustomListContactAdapter contactAdapter;
	private TextView tvNotes,tvReceiveVoiceMessageTitle,textView3;
	private ListView lvContact;
	private Config cfg, cfgTypeReply, cfgisreceivevoicemessage, cfgDelayTime,
			cfgAutoSync, cfgTypeSync, cfgSmsDelete, cfgRRDelete;
	Spinner spDelayTimes;
	// Media player, Media recorder
	private final String AUDIO_RECORDER_FOLDER = "VoiceRecord";
	public static final String FILE_DIRECTORY = "softtech";
	private final String AUDIO_RECORDER_FOLDER_ALLCALLS = "allcalls";
	private final String AUDIO_RECORDER_FOLDER_FAVORITES = "favorites";
	private File folder;
	private File files[];
	private File folder_favorites;
	private File files_favorites[];
	private List<RowRecord> list;
	private List<RowVoiceRecorded> listRowVoiceRecorded;
	private List<RowVoiceRecorded> listRowVoiceRecorded_favorites;
	private ToggleButton btRecording;
	private TextView tvTimeRecorded;
	private long mStartTime;
	private AudioManager am;
	private MediaRecorder recorder = null;
	private MediaPlayer player = null;
	private Handler mHandler;
	private String filepath;
	Button start, pause, stop;
	Dialog dialog;
	ToggleButton btnSpeaker;
	private SeekBar volumeControl = null;
	Handler seekHandler = new Handler();
	int progressChanged = 0;
	
	// END - Media player
	
	
	/**
	 * Layout Timing
	 */
	
	private int isInitViewTiming = 0;
	private ListView lvTiming;
	private ItemTimingAdapter adapterTiming;
	List<Timer> listTimer;
	
	static int mDelayTime = 10000;
	/**
	 * Layout Purchase
	 */
	private int isInitViewPurchase = 0;
	private Button btPurchase;
	/**
	 * End
	 */
	private Button btRateApp;
	
	IInAppBillingService mService;
	// Ads Zone for Free Version
	private InterstitialAd interstitial;
	private AdView adViewSettingOne,adViewSettingTwo,adViewSettingThree,adViewSMS,adViewRecord,adViewAbout,adViewListenVoice;
	
	private String path_record;
	private TextView tvFromContact, tvDuration;

	private RowVoiceRecorderListComparator mSortRowVoiceRecorderByName = RowVoiceRecorderListComparator
			.getNameFirst(true, true);
	private RowVoiceRecorderListComparator mSortRowVoiceRecorderByTime = RowVoiceRecorderListComparator
			.getNameFirst(false, false);

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		if(requestCode == 10001){
			if (mHelper != null && !mHelper.handleActivityResult(requestCode, 
		              resultCode, data)) {     
		    	      super.onActivityResult(requestCode, resultCode, data);
		    }
		}else if (requestCode == REQUEST_CODE_DIALOG_ADD_SMS) {

			if (resultCode == -1) {

				updateSms();

			} else {
			}
		} else if (requestCode == REQUEST_CODE_DIALOG_EDIT_SMS) {
			if (resultCode == RESULT_OK) {

				updateSms();

				// save sms to database
			} else {

			}
		} else if (requestCode == REQUEST_CODE_DIALOG_EDIT_RECORD) {
			if (resultCode == RESULT_OK) {

				updateListRecord();
			}
		} else if (requestCode == REQUEST_CODE_DIALOG_ADD_RECORD) {
			if (resultCode == RESULT_OK) {

				updateListRecord();
			} else {
				File file = new File(path_record);
				if (file.exists()) {

					file.delete();
				}
			}
		} else if (requestCode == REQUEST_LINK_TO_DBX_MAINACTIVITY) {
			if (resultCode == RESULT_OK) {
				// success
				mDropboxApi.linkAccountToFileFS();

				linkToDropbox = 1;

			} else {
				// link dropbox fail
			}
		} else if(requestCode == REQUEST_CODE_ADD_SCHEDULE) {
			if(resultCode == RESULT_OK){
				updateListTimer();
			}else{
				
			}
		} else if(requestCode == REQUEST_CODE_EDT_SCHEDULE){
			if(resultCode == RESULT_OK){
				updateListTimer();
			}
		}else {
			super.onActivityResult(requestCode, resultCode, data);
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);

		mContext = this;
		setSharedPreferences(true);
		dbHandler = new DatabaseHandler(mContext);
		cfg = dbHandler.getConfig(1);
		cfgTypeReply = dbHandler.getConfig(2);
		cfgAutoSync = dbHandler.getConfig(3);
		cfgTypeSync = dbHandler.getConfig(4);
		cfgTypeRecord = dbHandler.getConfig(5); // contact
		cfgisreceivevoicemessage = dbHandler.getConfig(6);
		cfgDelayTime = dbHandler.getConfig(7);
		cfgSmsDelete = dbHandler.getConfigByKeyWord("delmsgcheck");
		filepath = Environment.getExternalStorageDirectory().getPath();
		if (mDropboxApi == null) {
			try{
				mDropboxApi = new DropboxApi(mContext);
				mDropboxApi.registerAccountDropbox();
			}catch(Exception e){
				e.printStackTrace();
			}
			
		}
		loadData();
		initView();    
		if(hasConnections() && isPurchased==false){
			
			initPurchased();
			
			Handler handler = new Handler();
			handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					loadAds();
				}
			}, mDelayTime); // Time > 10s.
		}
		
	}
	public void loadAds(){
		interstitial = new InterstitialAd(this);
		AdRequest ads = new AdRequest.Builder().build();
		interstitial.setAdUnitId("ca-app-pub-2100208056165316/9348312789");
		interstitial.loadAd(ads);
		
		interstitial.setAdListener(new AdListener() {
	
			@Override
			public void onAdClosed() {
				
				super.onAdClosed();
				//test handler
				android.os.Message msg=new android.os.Message();
				Bundle b=new Bundle();
				b.putBoolean("showMe", true);
				msg.setData(b);
				handle1.sendMessage(msg);
			}
		});
		
		Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				displayInterstitial();
			}
		}, mDelayTime); // Time > 10s.
	}
	private void initView() {

		actionBar = getSupportActionBar();

		// actionBar.setIcon(R.drawable.ic_launcher);

		actionBar.setBackgroundDrawable(new ColorDrawable(colorActionBarSMS));

		// find view
		viewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper);

		initViewMain();

//		initViewAnswerBySms();
	}

	private void initViewMain() {

		int x = getScreenHeight(1);
		int y = getScreenHeight(0);

		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		params.addRule(RelativeLayout.CENTER_HORIZONTAL);

		if (x > y) {
			params.setMargins((int) convertDpToPixel(80), (int) (x * 0.35), 0,
					0);
		} else {
			params.setMargins((int) convertDpToPixel(80), (int) (y * 0.35), 0,
					0);
		}

		tvSms = (TextView) findViewById(R.id.tv_sms);

		tvSms.setLayoutParams(params);

		tvRecord = (TextView) findViewById(R.id.tv_record);

		tvListen = (TextView) findViewById(R.id.tv_listen);

		tvSetting = (TextView) findViewById(R.id.tv_setting);

		tvAbout = (TextView) findViewById(R.id.tv_about);

		tvSchedule = (TextView) findViewById(R.id.tv_schedule);
		
		// handle onclick
		eventClickMainLayout();
	}

	public float convertDpToPixel(float dp) {
		Resources resources = mContext.getResources();
		DisplayMetrics metrics = resources.getDisplayMetrics();
		float px = dp * (metrics.densityDpi / 160f);
		return px;
	}

	public float convertPixelsToDp(float px) {
		Resources resources = mContext.getResources();
		DisplayMetrics metrics = resources.getDisplayMetrics();
		float dp = px / (metrics.densityDpi / 160f);
		return dp;
	}

	/*
	 * getting screen width
	 */
	@SuppressWarnings("deprecation")
	@SuppressLint("NewApi")
	public int getScreenHeight(int width) {

		WindowManager wm = (WindowManager) mContext
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = wm.getDefaultDisplay();

		final Point point = new Point();
		try {
			display.getSize(point);
		} catch (java.lang.NoSuchMethodError ignore) { // Older device
			point.x = display.getWidth();
			point.y = display.getHeight();
		}

		if (width == 1) {
			return point.x;
		}

		return point.y;
	}

	private void eventClickMainLayout() {

		tvSms.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				

				// set title action bar
				actionBar.setTitle(tvSms.getText());
				actionBar.setBackgroundDrawable(new ColorDrawable(
						colorActionBarSMS));

				if (mMenu != null) {

					onPrepareOptionsMenu(mMenu);

					MenuItem item_add_sms = mMenu
							.findItem(R.id.action_add_item_sms);

					item_add_sms.setVisible(true);
				}

				showPage(R.id.view_sms);

				if (isInitViewAnserBySms == 0) {

					initViewAnswerBySms();
				}

				if (adapterSms != null) {
					adapterSms.notifyDataSetChanged();
				}
			}
		});

		tvRecord.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				

				// set title action bar
				actionBar.setTitle(tvRecord.getText());
				actionBar.setBackgroundDrawable(new ColorDrawable(
						colorActionBarSMS));

				if (isInitViewRecord == 0) {

					initViewAnswerByRecord();
				}

				showPage(R.id.view_record);
			}
		});

		tvListen.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				

				// set title action bar
				actionBar.setTitle("Listen Voice Message");
				actionBar.setBackgroundDrawable(new ColorDrawable(
						colorActionBarSMS));

				onPrepareOptionsMenu(mMenu);

				MenuItem item_sort = mMenu
						.findItem(R.id.action_sort_voice_recorde);

				item_sort.setVisible(true);

				MenuItem item_search = mMenu.findItem(R.id.action_menu_search);

				item_search.setVisible(true);

				SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
				SearchView searchView = (SearchView) item_search.getActionView();
				searchView.setSearchableInfo(searchManager
						.getSearchableInfo(getComponentName()));
				//searchView.setIconifiedByDefault(false);

				SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener() {
					@Override
					public boolean onQueryTextChange(String newText) {
						// Send request o day
						Log.d("TAG","All call search !!!");
						adapterAllCalls.getFilter().filter(newText);
						return true;
					}

					@Override
					public boolean onQueryTextSubmit(String query) {
						// this is your adapter that will be filtered
						// Log.d("QUERY", "Submit query ="+query);
						return true;
					}
				};
				searchView.setOnQueryTextListener(textChangeListener);
				
				if (isInitViewListen == 0) {
					initViewListenLayout();
				}

				showPage(R.id.view_listen);
			}
		});

		tvSetting.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				
				initViewSettingLayout();

				showPage(R.id.view_setting);
			}
		});
		tvAbout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				

				// set title action bar
				actionBar.setTitle(tvAbout.getText());
				actionBar.setBackgroundDrawable(new ColorDrawable(
						colorActionBarSMS));
				showPage(R.id.view_about);
				adViewAbout = (AdView) findViewById(R.id.adViewAbout);
			   
				if(hasConnections() && isPurchased==false){
					Handler handler = new Handler();
					handler.postDelayed(new Runnable() {
						@Override
						public void run() {
							AdRequest adRequest = new AdRequest.Builder().build();
							adViewAbout.loadAd(adRequest);
						}
					}, 10000); // Time > 10s.
					
				}else{
					adViewAbout.setVisibility(View.GONE);
				}
			}
		});
		
		tvSchedule.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				
				actionBar.setTitle("Timing");
				actionBar.setBackgroundDrawable(new ColorDrawable(
						colorActionBarSMS));
				if(isPurchased){
					if(isInitViewTiming == 0){

						initViewTiming();
						
						isInitViewTiming = 1;
						
					}
					
					if (mMenu != null) {

						onPrepareOptionsMenu(mMenu);

						MenuItem item_add_sms = mMenu
								.findItem(R.id.action_add_item_sms);

						item_add_sms.setVisible(true);
					}

					showPage(R.id.view_schedule);
					
					updateListTimer();
				}else{
					if(isInitViewPurchase == 0){

						initViewPurchase();
						
						isInitViewPurchase = 1;
						
					}
					showPage(R.id.view_purchase);
				}

			}
		});
		
	}

	// action share : filter fb, tw, g+, defaul send by mail or add to Note
	public void onShareClick(View v) {
		// Resources resources = getResources();

		String urlToShare = "An application that automatically record and reply incoming calls !\n\nhttps://play.google.com/store/apps/details?id="
				+ getPackageName();// change link to app store
		Intent intent = new Intent(Intent.ACTION_SEND);
		intent.setType("text/plain");
		intent.putExtra(Intent.EXTRA_TEXT, urlToShare);

		if (v.getId() == R.id.btShareFb) {

			// See if official Facebook app is found
			boolean facebookAppFound = false;
			List<ResolveInfo> matches = getPackageManager()
					.queryIntentActivities(intent, 0);
			for (ResolveInfo info : matches) {
				if (info.activityInfo.packageName.contains("com.facebook")) {
					intent.setPackage(info.activityInfo.packageName);
					facebookAppFound = true;
					break;
				}
			}

			// As callback, launch sharer.php in a browser
			if (!facebookAppFound) {
				startActivity(Intent.createChooser(intent, "Share with"));
			} else {
				startActivity(intent);
			}

		} else if (v.getId() == R.id.btShareGG) {
			 Intent shareIntent = new PlusShare.Builder(this)
	          .setType("text/plain")
	          .setText("An application that automatically record and reply incoming calls.")
	          .setContentUrl(Uri.parse("https://play.google.com/store/apps/details?id="
				+ getPackageName()))
	          .getIntent();

	      startActivityForResult(shareIntent, 0);
		} else if (v.getId() == R.id.btShareTw) {
			boolean facebookAppFound = false;
			List<ResolveInfo> matches = getPackageManager()
					.queryIntentActivities(intent, 0);
			for (ResolveInfo info : matches) {
				if (info.activityInfo.packageName.contains("twitter")) {
					intent.setPackage(info.activityInfo.packageName);
					facebookAppFound = true;
					break;
				}
			}

			// As callback, launch sharer.php in a browser
			if (!facebookAppFound) {
				startActivity(Intent.createChooser(intent, "Share with"));
			} else {
				startActivity(intent);
			}
		} else {
			startActivity(Intent.createChooser(intent, "Share with"));
		}

		// Intent emailIntent = new Intent();
		// emailIntent.setAction(Intent.ACTION_SEND);
		// // Native email client doesn't currently support HTML, but it doesn't
		// // hurt to try in case they fix it
		// emailIntent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml("email"));
		// emailIntent.putExtra(Intent.EXTRA_SUBJECT, "subject");
		// emailIntent.setType("message/rfc822");
		//
		// PackageManager pm = getPackageManager();
		// Intent sendIntent = new Intent(Intent.ACTION_SEND);
		// sendIntent.setType("text/plain");
		// sendIntent.putExtra(Intent.EXTRA_TEXT,
		// "An application that automatically record and reply incoming calls !\n\nhttps://play.google.com/store/apps/details?id="
		// + getPackageName());// change link to app store
		// sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		//
		// Intent openInChooser = Intent.createChooser(emailIntent, "email");
		//
		// List<ResolveInfo> resInfo = pm.queryIntentActivities(sendIntent, 0);
		// List<LabeledIntent> intentList = new ArrayList<LabeledIntent>();
		// for (int i = 0; i < resInfo.size(); i++) {
		// // Extract the label, append it, and repackage it in a LabeledIntent
		// ResolveInfo ri = resInfo.get(i);
		// String packageName = ri.activityInfo.packageName;
		// Log.e("package", packageName);
		// if (packageName.contains("android.email")) {
		// emailIntent.setPackage(packageName);
		// } else if (packageName.contains("twitter")
		// || packageName.contains("facebook")
		// || packageName.contains("mms")
		// || packageName.contains("android.gm")) {
		// Intent intent = new Intent();
		// intent.setComponent(new ComponentName(packageName,
		// ri.activityInfo.name));
		// intent.setAction(Intent.ACTION_SEND);
		// intent.setType("text/plain");
		// if (packageName.contains("twitter")) {
		// intent.putExtra(Intent.EXTRA_TEXT, "Twitter");
		// } else if (packageName.contains("facebook")) {
		// intent.putExtra(Intent.EXTRA_TEXT, "facebook");
		// } else if (packageName.contains("mms")) {
		// intent.putExtra(Intent.EXTRA_TEXT, "sms");
		// } else if (packageName.contains("android.gm")) {
		// intent.putExtra(Intent.EXTRA_TEXT,
		// Html.fromHtml("email_gmail"));
		// intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
		// intent.setType("message/rfc822");
		// }
		//
		// intentList.add(new LabeledIntent(intent, packageName, ri
		// .loadLabel(pm), ri.icon));
		// }
		// }
		//
		// // convert intentList to array
		// LabeledIntent[] extraIntents = intentList
		// .toArray(new LabeledIntent[intentList.size()]);
		//
		// openInChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
		// startActivity(openInChooser);
	}

	private void initViewAnswerBySms() {

		isInitViewAnserBySms = 1;

		lvContent = (ListView) findViewById(R.id.lv_sms);

		tvHeaderContent = (TextView) findViewById(R.id.tv_header_content);

		tvHeaderTitle = (TextView) findViewById(R.id.tv_header_title);

		// imgHeader = (ImageView) findViewById(R.id.img_header_sms);
		
		adViewSMS = (AdView) findViewById(R.id.adViewAnswerSMS);
		if(hasConnections() && isPurchased==false){
			Handler handler = new Handler();
			handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					AdRequest adRequest = new AdRequest.Builder().build();
					adViewSMS.loadAd(adRequest);
				}
			}, 10000); // Time > 10s.
			
		}else{
			adViewSMS.setVisibility(View.GONE);
		}
		adapterSms = new ItemSmsAdapter(MainActivity.this);

		lvContent.setAdapter(adapterSms);

		// adapterSms.updateListMessage(-10, -10);

		updateSmsSub();
	}

	private void initViewAnswerByRecord() {
		mHandler = new Handler();
		isInitViewRecord = 1;
		adViewRecord = (AdView) findViewById(R.id.adViewAnswerRecord);
		if(hasConnections() && isPurchased==false){

			Handler handler = new Handler();
			handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					AdRequest adRequest = new AdRequest.Builder().build();
					adViewRecord.loadAd(adRequest);
				}
			}, 10000); // Time > 10s.
			
		}else{
			adViewRecord.setVisibility(View.GONE);
		}
		lvRecord = (ListView) findViewById(R.id.lv_record);
		// Get list file in folder fill into adapter
		folder = new File(filepath, FILE_DIRECTORY + "/"
				+ AUDIO_RECORDER_FOLDER);
		if (!folder.exists()) {
			folder.mkdirs();
		}
		files = folder.listFiles();
		list = new ArrayList<RowRecord>();
		for (File f : files) {
			if (f.getName().endsWith(".mp3") && f.getName().split("-").length > 2 && f.getName().split("-")[1].length() > 2) {
				// do something with them, add them to list or whatever
				list.add(new RowRecord(f.getName(), f.getAbsolutePath()));
			}
		}
		adapterRecord = new ItemRecordAdapter(mContext, list);
		lvRecord.setAdapter(adapterRecord);

		lvRecord.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				
				// play record
				am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
				player = new MediaPlayer();
				player.setAudioStreamType(AudioManager.STREAM_MUSIC);

				dialog = new Dialog(MainActivity.this, R.style.mydialogstyle);
				dialog.getWindow();
				dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
				dialog.setContentView(R.layout.media_player);
				dialog.setCanceledOnTouchOutside(true);
				dialog.setCancelable(true);
				dialog.setOnDismissListener(new OnDismissListener() {

					@Override
					public void onDismiss(DialogInterface dialog) {
						
						am.setSpeakerphoneOn(false);
						volumeControl = null;
						if (player != null) {
							player.stop();
							player.release();
							player = null;
						}
					}
				});

				try {
					player.setDataSource(list.get(position)
							.getmFilePath());
				} catch (IllegalArgumentException e) {
					
					e.printStackTrace();
				} catch (SecurityException e) {
					
					e.printStackTrace();
				} catch (IllegalStateException e) {
					
					e.printStackTrace();
				} catch (IOException e) {
					
					e.printStackTrace();
				}
				try {
					player.prepare();
				} catch (IllegalStateException e) {
					
					e.printStackTrace();
				} catch (IOException e) {
					
					e.printStackTrace();
				}

				start = (Button) dialog.findViewById(R.id.btnStart);
				pause = (Button) dialog.findViewById(R.id.btnPause);
				stop = (Button) dialog.findViewById(R.id.btnStop);
				btnSpeaker = (ToggleButton) dialog
						.findViewById(R.id.btnSpeaker);
				tvFromContact = (TextView) dialog
						.findViewById(R.id.tvFromContent);
				tvDuration = (TextView) dialog
						.findViewById(R.id.tvDurationContent);

				tvFromContact.setText(list.get(position)
						.getmFileName());
				tvDuration.setText(getTimeString(player.getDuration()));
				// Seek bar volume control
				volumeControl = (SeekBar) dialog.findViewById(R.id.seekBar);
				volumeControl
						.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

							public void onProgressChanged(SeekBar seekBar,
									int progress, boolean fromUser) {
								progressChanged = progress;
							}

							public void onStartTrackingTouch(SeekBar seekBar) {
								
							}

							public void onStopTrackingTouch(SeekBar seekBar) {

							}
						});

				start.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						player.start();
						am.setSpeakerphoneOn(true);
						int volume_level = am
								.getStreamVolume(AudioManager.STREAM_MUSIC);
						int max_volume = am
								.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
						if (volume_level < max_volume) {
							am.setStreamVolume(AudioManager.STREAM_MUSIC,
									max_volume, AudioManager.FLAG_SHOW_UI);
						}
						volumeControl.setMax(player.getDuration());
						seekUpdation();
					}
				});
				pause.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						player.pause();
					}
				});
				stop.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						dialog.dismiss();
					}
				});

				btnSpeaker
						.setOnCheckedChangeListener(new OnCheckedChangeListener() {

							@Override
							public void onCheckedChanged(
									CompoundButton buttonView, boolean isChecked) {
								
								if (isChecked) {
									btnSpeaker.setChecked(true);
									if (!am.isSpeakerphoneOn()) {
										am.setSpeakerphoneOn(true);
									}

								} else {
									btnSpeaker.setChecked(false);
									if (am.isSpeakerphoneOn()) {
										am.setSpeakerphoneOn(false);
									}
								}
							}
						});

				dialog.show();
			}
		});

		registerForContextMenu(lvRecord);

		btRecording = (ToggleButton) findViewById(R.id.toggle_recording);
		// btPausing = (ToggleButton) findViewById(R.id.toggle_pausing);
		// btStop = (Button) findViewById(R.id.bt_stop);
		tvTimeRecorded = (TextView) findViewById(R.id.tv_time_record);
		// Perform recording here

		btRecording.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				
				if (isChecked) {
					startRecording();
					tvTimeRecorded.setText("00:00");
					mStartTime = SystemClock.uptimeMillis();
					mHandler.removeCallbacks(mUpdateTimeTask);
					mHandler.postDelayed(mUpdateTimeTask, 1000);
				} else {
					stopRecording();
					tvTimeRecorded.setText("00:00");

					Intent intent = new Intent(mContext, DialogAddSms.class);

					intent.putExtra("requestCode",
							MainActivity.REQUEST_CODE_DIALOG_ADD_RECORD);

					intent.putExtra("pathRecord", path_record);

					startActivityForResult(intent,
							REQUEST_CODE_DIALOG_ADD_RECORD);
				}
			}
		});

	}

	private void initViewListenLayout() {

		isInitViewListen = 1;
		adViewListenVoice = (AdView) findViewById(R.id.adViewListenVoice);
		if(hasConnections() && isPurchased==false){
			Handler handler = new Handler();
			handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					AdRequest adRequest = new AdRequest.Builder().build();
					adViewListenVoice.loadAd(adRequest);
				}
			}, 10000); // Time > 10s.
			
		}else{
			adViewListenVoice.setVisibility(View.GONE);
		}
		tabs = (TabHost) findViewById(android.R.id.tabhost);
		tabs.setup();
		TabHost.TabSpec spec = tabs.newTabSpec("tabAllCalls");

		/**
		 * tab all calls
		 */
		spec.setContent(R.id.tabAllCalls);
		spec.setIndicator("All Calls");
		tabs.addTab(spec);
		listContact = new ArrayList<Contact>();
		getContacts();
		// Get all file record in folder favorites
		folder_favorites = new File(filepath, FILE_DIRECTORY + "/"
				+ AUDIO_RECORDER_FOLDER_FAVORITES);
		if (!folder_favorites.exists()) {
			folder_favorites.mkdirs();
		}
		files_favorites = folder_favorites.listFiles();
		listRowVoiceRecorded_favorites = new ArrayList<RowVoiceRecorded>();
		RowVoiceRecorded voice_f = null;
		for (File f : files_favorites) {
			boolean matched = false;
			String ss[] = f.getName().split("-");
			boolean isSync = false;
			if (ss[2].compareTo(Constant.ISSYNC1) == 0) {
				isSync = true;
			}
			int i = 0;
			for (Contact aContact : listContact) {
				if (ss[1].trim() != null
						&& aContact.get_phone_number().trim()
								.contains(ss[1].trim())) {

					voice_f = new RowVoiceRecorded(listContact.get(i)
							.get_name(), f.getAbsolutePath(),
							Long.parseLong(ss[0].trim()), ss[1].trim(), isSync);
					matched = true;
					break;
				}
				i++;
			}
			if (!matched) {

				voice_f = new RowVoiceRecorded("Unknown", f.getAbsolutePath(),
						Long.parseLong(ss[0].trim()), ss[1].trim(), isSync);
			}
			
//			Log.e("voice_f SYNC", voice_f.getIsSync()+"");
			listRowVoiceRecorded_favorites.add(voice_f);
		}

		if (listRowVoiceRecorded_favorites != null) {
			Collections.sort(listRowVoiceRecorded_favorites,
					mSortRowVoiceRecorderByTime);
		}
		
		adapterAllCalls = new ItemVoiceRecordAdapter(mContext,
				listRowVoiceRecorded_favorites);
		
		lvFavorites = (ListView) tabs.findViewById(R.id.lv_favorites);
		lvFavorites.setAdapter(adapterAllCalls);
		registerForContextMenu(lvFavorites);
		lvFavorites.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
				player = new MediaPlayer();
				player.setAudioStreamType(AudioManager.STREAM_MUSIC);

				dialog = new Dialog(MainActivity.this, R.style.mydialogstyle);
				dialog.getWindow();
				dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
				dialog.setContentView(R.layout.media_player);
				dialog.setCanceledOnTouchOutside(true);
				dialog.setCancelable(true);
				dialog.setOnDismissListener(new OnDismissListener() {

					@Override
					public void onDismiss(DialogInterface dialog) {
						
						am.setSpeakerphoneOn(false);
						volumeControl = null;
						if (player != null) {
							player.stop();
							player.release();
							player = null;
						}
					}
				});

				try {
					player.setDataSource(listRowVoiceRecorded.get(position)
							.getmPath());
				} catch (IllegalArgumentException e) {
					
					e.printStackTrace();
				} catch (SecurityException e) {
					
					e.printStackTrace();
				} catch (IllegalStateException e) {
					
					e.printStackTrace();
				} catch (IOException e) {
					
					e.printStackTrace();
				}
				try {
					player.prepare();
				} catch (IllegalStateException e) {
					
					e.printStackTrace();
				} catch (IOException e) {
					
					e.printStackTrace();
				}

				start = (Button) dialog.findViewById(R.id.btnStart);
				pause = (Button) dialog.findViewById(R.id.btnPause);
				stop = (Button) dialog.findViewById(R.id.btnStop);
				btnSpeaker = (ToggleButton) dialog
						.findViewById(R.id.btnSpeaker);
				tvFromContact = (TextView) dialog
						.findViewById(R.id.tvFromContent);
				tvDuration = (TextView) dialog
						.findViewById(R.id.tvDurationContent);

				tvFromContact.setText(listRowVoiceRecorded.get(position)
						.getmName());
				tvDuration.setText(getTimeString(player.getDuration()));
				// Seek bar volume control
				volumeControl = (SeekBar) dialog.findViewById(R.id.seekBar);
				volumeControl
						.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

							public void onProgressChanged(SeekBar seekBar,
									int progress, boolean fromUser) {
								progressChanged = progress;
							}

							public void onStartTrackingTouch(SeekBar seekBar) {
								
							}

							public void onStopTrackingTouch(SeekBar seekBar) {

							}
						});

				start.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						player.start();
						am.setSpeakerphoneOn(true);
						int volume_level = am
								.getStreamVolume(AudioManager.STREAM_MUSIC);
						int max_volume = am
								.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
						if (volume_level < max_volume) {
							am.setStreamVolume(AudioManager.STREAM_MUSIC,
									max_volume, AudioManager.FLAG_SHOW_UI);
						}
						volumeControl.setMax(player.getDuration());
						seekUpdation();
					}
				});
				pause.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						player.pause();
					}
				});
				stop.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						dialog.dismiss();
					}
				});

				btnSpeaker
						.setOnCheckedChangeListener(new OnCheckedChangeListener() {

							@Override
							public void onCheckedChanged(
									CompoundButton buttonView, boolean isChecked) {
								
								if (isChecked) {
									btnSpeaker.setChecked(true);
									if (!am.isSpeakerphoneOn()) {
										am.setSpeakerphoneOn(true);
									}

								} else {
									btnSpeaker.setChecked(false);
									if (am.isSpeakerphoneOn()) {
										am.setSpeakerphoneOn(false);
									}
								}
							}
						});

				dialog.show();

			}
		});
		// Get all file record in folder allcalls
		folder = new File(filepath, FILE_DIRECTORY + "/"
				+ AUDIO_RECORDER_FOLDER_ALLCALLS);
		if (!folder.exists()) {
			folder.mkdirs();
		}
		files = folder.listFiles();

		for (File f : files) {
			
			Util.moveFile(f.getAbsolutePath(), f.getAbsolutePath().replace(Constant.ISSYNC1, Constant.ISSYNC0));
		}
		
		listRowVoiceRecorded = new ArrayList<RowVoiceRecorded>();
		RowVoiceRecorded voice = null;
		for (File f : files) {

			boolean matched = false;
			String ss[] = f.getName().split("-");
			boolean isSync = false;

			if (ss[2].compareTo(Constant.ISSYNC1) == 0) {
				isSync = true;
			}

			int i = 0;
			for (Contact aContact : listContact) {
				if (ss[1].trim() != null
						&& aContact.get_phone_number().trim()
								.contains(ss[1].trim())) {

					voice = new RowVoiceRecorded(listContact.get(i).get_name(),
							f.getAbsolutePath(), Long.parseLong(ss[0].trim()),
							ss[1].trim(), isSync);
					matched = true;
					break;
				}
				i++;
			}
			if (!matched) {

				voice = new RowVoiceRecorded("Unknown", f.getAbsolutePath(),
						Long.parseLong(ss[0].trim()), ss[1].trim(), isSync);
			}
			
			listRowVoiceRecorded.add(voice);
		}
		// Noi 2 arrayList
		listRowVoiceRecorded.addAll(listRowVoiceRecorded_favorites);
		if (listRowVoiceRecorded != null) {
			Collections.sort(listRowVoiceRecorded, mSortRowVoiceRecorderByTime);
		}

		lvAllCalls = (ListView) tabs.findViewById(R.id.lv_allcalls);
		adapterAllCalls = new ItemVoiceRecordAdapter(mContext,
				listRowVoiceRecorded);
		
		lvAllCalls.setAdapter(adapterAllCalls);
		registerForContextMenu(lvAllCalls);
		lvAllCalls.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
				player = new MediaPlayer();
				player.setAudioStreamType(AudioManager.STREAM_MUSIC);

				dialog = new Dialog(MainActivity.this, R.style.mydialogstyle);
				dialog.getWindow();
				dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
				dialog.setContentView(R.layout.media_player);
				dialog.setCanceledOnTouchOutside(true);
				dialog.setCancelable(true);
				dialog.setOnDismissListener(new OnDismissListener() {

					@Override
					public void onDismiss(DialogInterface dialog) {
						
						am.setSpeakerphoneOn(false);
						volumeControl = null;
						if (player != null) {
							player.stop();
							player.release();
							player = null;
						}
					}
				});

				try {
					player.setDataSource(listRowVoiceRecorded.get(position)
							.getmPath());
				} catch (IllegalArgumentException e) {
					
					e.printStackTrace();
				} catch (SecurityException e) {
					
					e.printStackTrace();
				} catch (IllegalStateException e) {
					
					e.printStackTrace();
				} catch (IOException e) {
					
					e.printStackTrace();
				}
				try {
					player.prepare();
				} catch (IllegalStateException e) {
					
					e.printStackTrace();
				} catch (IOException e) {
					
					e.printStackTrace();
				}

				start = (Button) dialog.findViewById(R.id.btnStart);
				pause = (Button) dialog.findViewById(R.id.btnPause);
				stop = (Button) dialog.findViewById(R.id.btnStop);
				btnSpeaker = (ToggleButton) dialog
						.findViewById(R.id.btnSpeaker);
				tvFromContact = (TextView) dialog
						.findViewById(R.id.tvFromContent);
				tvDuration = (TextView) dialog
						.findViewById(R.id.tvDurationContent);

				tvFromContact.setText(listRowVoiceRecorded.get(position)
						.getmName());
				tvDuration.setText(getTimeString(player.getDuration()));
				// Seek bar volume control
				volumeControl = (SeekBar) dialog.findViewById(R.id.seekBar);
				volumeControl
						.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

							public void onProgressChanged(SeekBar seekBar,
									int progress, boolean fromUser) {
								progressChanged = progress;
							}

							public void onStartTrackingTouch(SeekBar seekBar) {
								
							}

							public void onStopTrackingTouch(SeekBar seekBar) {

							}
						});

				start.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						player.start();
						am.setSpeakerphoneOn(true);
						int volume_level = am
								.getStreamVolume(AudioManager.STREAM_MUSIC);
						int max_volume = am
								.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
						if (volume_level < max_volume) {
							am.setStreamVolume(AudioManager.STREAM_MUSIC,
									max_volume, AudioManager.FLAG_SHOW_UI);
						}
						volumeControl.setMax(player.getDuration());
						seekUpdation();
					}
				});
				pause.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						player.pause();
					}
				});
				stop.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						dialog.dismiss();
					}
				});

				btnSpeaker
						.setOnCheckedChangeListener(new OnCheckedChangeListener() {

							@Override
							public void onCheckedChanged(
									CompoundButton buttonView, boolean isChecked) {
								
								if (isChecked) {
									btnSpeaker.setChecked(true);
									if (!am.isSpeakerphoneOn()) {
										am.setSpeakerphoneOn(true);
									}

								} else {
									btnSpeaker.setChecked(false);
									if (am.isSpeakerphoneOn()) {
										am.setSpeakerphoneOn(false);
									}
								}
							}
						});

				dialog.show();
			}

		});

		/**
		 * tab Favorites
		 */

		spec = tabs.newTabSpec("tabFavorites");
		spec.setContent(R.id.tabFavorites);
		spec.setIndicator("Favorites");
		tabs.addTab(spec);

		/**
		 * tab Filter
		 */
		// spec = tabs.newTabSpec("tabFilters");
		// spec.setContent(R.id.tabFilters);
		// spec.setIndicator("Filter");
		// tabs.addTab(spec);

		tabs.setCurrentTab(0);
	}

	private void initViewSettingLayout() {
		contactAdapter = new CustomListContactAdapter(mContext);
		mViewFlipper = (ViewFlipper) findViewById(R.id.view_flipper);
		onPrepareOptionsMenu(mMenu);
		item_search = mMenu.findItem(R.id.action_menu_search);
		
		SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
		SearchView searchView = (SearchView) item_search.getActionView();
		searchView.setSearchableInfo(searchManager
				.getSearchableInfo(getComponentName()));
		//searchView.setIconifiedByDefault(false);

		SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener() {
			@Override
			public boolean onQueryTextChange(String newText) {
				Log.d("TAG","Contact search !!!");
				contactAdapter.getFilter().filter(newText);	
				return true;
			}

			@Override
			public boolean onQueryTextSubmit(String query) {
				// this is your adapter that will be filtered
				// Log.d("QUERY", "Submit query ="+query);
				return true;
			}
		};
		searchView.setOnQueryTextListener(textChangeListener);
		
		if (isInitViewSetting == 0) {
			settingTabGeneral();

			settingTabContacts();

			settingTabSyncToDropbox();

			setEventClickButton();

			setEventClickButtonTabGeneral();

			setEventClickButtonTabContacts();

			setEventClickButtonTabSyncToDropbox();

			isInitViewSetting = 1;
		}

		if (positionTab == 0) {
			btGeneralSetting
					.setBackgroundResource(R.drawable.selector_hometab_btselected);
		} else if (positionTab == 1) {
			item_search.setVisible(true);
			isTabContact = 1;
			btSelectContacts
					.setBackgroundResource(R.drawable.selector_hometab_btselected);
		} else if (positionTab == 2) {
			btSyncToDropbox
					.setBackgroundResource(R.drawable.selector_hometab_btselected);
		}
		//Log.d("ENABLEAPP", "Enable app = " + cfg.get_value());
		if (cfg.get_value() == 1) {
			btEnableCall.setChecked(true);
		} else {
			btEnableCall.setChecked(false);
		}

		cfgSmsDelete = dbHandler.getConfigByKeyWord("delmsgcheck");

		if (cfgSmsDelete.get_value() == 1) {
			toggleEnalbeAskBeforeDel.setChecked(false);
		} else {
			toggleEnalbeAskBeforeDel.setChecked(true);
		}

		cfgRRDelete = dbHandler.getConfigByKeyWord("delrrcheck");

		if (cfgRRDelete.get_value() == 1) {
			toggleEnalbeAskBeforeDelRR.setChecked(false);
		} else {
			toggleEnalbeAskBeforeDelRR.setChecked(true);
		}

		// Init toggle button when get view here
		//Log.d("TYPEREPLY", "Type reply = " + cfgTypeReply.get_value());
		if (cfgTypeReply.get_value() == 1) {
			radReplyAudio.setChecked(true);
		} else {
			radReplySMS.setChecked(true);
		}
		//Log.d("RECEIVOICE",
		//		"Recei voice message = " + cfgisreceivevoicemessage.get_value());
		// Check in billing app here
		

		initPurchased();
	    if(isPurchased)
	    {
	      //Log.d("PURCHASR", "############ Product has purchase");
	      tvReceiveVoiceMessageTitle.setTextColor(Color.parseColor("#ffffff"));
	      textView3.setTextColor(Color.parseColor("#ffffff"));
	      btEnableReceiveVoiceMessage.setEnabled(true);
	      btBuyFullVersion.setEnabled(false);
	      btBuyFullVersion.setVisibility(View.GONE);
			if (cfgisreceivevoicemessage.get_value() == 1) {
				btEnableReceiveVoiceMessage.setChecked(true);
			} else {
				btEnableReceiveVoiceMessage.setChecked(false);
			}
	    }else{
	    	//Log.d("PURCHASR", "Chua purchase");
	    	btEnableReceiveVoiceMessage.setEnabled(false);
	    	btEnableReceiveVoiceMessage.setChecked(false);
	    	tvReceiveVoiceMessageTitle.setTextColor(Color.parseColor("#ff0000"));
	    	textView3.setTextColor(Color.parseColor("#ff0000"));
	    }
		

		//Log.d("DELAYTIME", "Delay time = " + cfgDelayTime.get_value());
		switch (cfgDelayTime.get_value()) {
		case 3:
			spDelayTimes.setSelection(0);
			break;
		case 4:
			spDelayTimes.setSelection(1);
			break;
		case 5:
			spDelayTimes.setSelection(2);
			break;
		case 6:
			spDelayTimes.setSelection(3);
			break;
		case 7:
			spDelayTimes.setSelection(4);
			break;
		case 8:
			spDelayTimes.setSelection(5);
			break;
		case 9:
			spDelayTimes.setSelection(6);
			break;
		case 10:
			spDelayTimes.setSelection(7);
			break;
		default:
			break;
		}
	}
	
	private void initViewTiming(){
		
		listTimer = dbHandler.getAllTimer();
		
		lvTiming = (ListView) findViewById(R.id.lv_schedule);
		
		adapterTiming = new ItemTimingAdapter(mContext, listTimer);
		
		lvTiming.setAdapter(adapterTiming);
		lvTiming.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				
				Intent intent = new Intent(mContext, AddSchedule.class);
				intent.putExtra("requestCode", REQUEST_CODE_EDT_SCHEDULE);
				intent.putExtra("TIMER_ID", listTimer.get(position).getId());
				startActivityForResult(intent, REQUEST_CODE_EDT_SCHEDULE);
			}
		});
	}
	
	private void initViewPurchase(){
		
		listTimer = dbHandler.getAllTimer();
		btPurchase = (Button) findViewById(R.id.btPurchase);	
		btPurchase.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(hasConnections()){
					buyClick(v);
				}else{
					alert("please connect to internet");
				}
				
			}
		});
	}
	
    void alert(String message) {
        AlertDialog.Builder bld = new AlertDialog.Builder(this);
        bld.setMessage(message);
        bld.setNeutralButton("OK", null);
        //Log.d(TAG, "Showing alert dialog: " + message);
        bld.create().show();
    }
	public void buyClick(View v) {
		 if (isPurchased == true) {
	            complain("You app is purchased!");
	            return;
	     }
		
		 String payload = "aaaaE$^%&%^&%&JKJKHJKHJK";
		 
		 if(mHelper == null || mHelper.equals(null)){
			 AsyncTask<Void, Void, Void> taskInitHelper = new AsyncTask<Void, Void, Void>(){

				 
				 
				@Override
				protected void onPreExecute() {
					initPurchased();
					super.onPreExecute();
				}

				@Override
				protected void onPostExecute(Void result) {
					super.onPostExecute(result);
					String payload = "aaaaE$^%&%^&%&JKJKHJKHJK";
					mHelper.launchPurchaseFlow(MainActivity.this, ITEM_SKU, RC_REQUEST,
			                mPurchaseFinishedListener, payload);
				}

				@Override
				protected Void doInBackground(Void... params) {
					// TODO Auto-generated method stub
					return null;
				}
				 
			 };
			 taskInitHelper.execute(null,null,null);
			 return;
		 }
		 
		 mHelper.launchPurchaseFlow(MainActivity.this, ITEM_SKU, RC_REQUEST,
	                mPurchaseFinishedListener, payload);

	}
	IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {

		@Override
		public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
			
			if (mHelper == null) return;
			if (result.isFailure()) {
				if(result.getResponse() == 7){
					isPurchased = true;
					saveData();
				}else{
					//complain("Loi khi purchase: " + result);
					complain("Something wrong, Connect to the internet as please try agian !!");
				}
                return;
            }
            if (!verifyDeveloperPayload(purchase)) {
                complain("Error purchasing. Authenticity verification failed.");
                return;
            }
            //Log.d(TAG, "Purchase successful.");

            if (purchase.getSku().equals(ITEM_SKU)) {
                //Log.d(TAG, "Purchase is gas. Starting gas consumption.");
                mHelper.consumeAsync(purchase, mConsumeFinishedListener);
            }else if(purchase.getSku().equals(ITEM_SKU2)){
            	//Log.d(TAG, "Purchase is gas. Starting gas consumption.");
            	mHelper.consumeAsync(purchase, mConsumeFinishedListener);
            }
		}
	};
		
	IabHelper.QueryInventoryFinishedListener mGotInventoryListener 
	   = new IabHelper.QueryInventoryFinishedListener() {
		   public void onQueryInventoryFinished(IabResult result,
		      Inventory inventory) {
			  if (mHelper == null) return;
		      if (result.isFailure()) {
			  // Handle failure
		    	  //Log.d(TAG, "Click buy button to reactive app");
		    	  if(result.getResponse() == 7){
						isPurchased = true;
						saveData();
					}else{
						//complain("Loi khi purchase: " + result);
						complain("Something wrong, Connect to the internet as please try agian !!");
					}
	                //return;
		      } 
		      
		      //Log.d(TAG, "Query inventory was successful.");
		      
		      // Check for gas delivery -- if we own gas, we should fill up the tank immediately
	            Purchase gasPurchase = inventory.getPurchase(ITEM_SKU);
	            Purchase gasPurchase2 = inventory.getPurchase(ITEM_SKU2);
	            if (gasPurchase != null && verifyDeveloperPayload(gasPurchase)) {
	                //Log.d(TAG, "We have gas. Consuming it.");
	                mHelper.consumeAsync(inventory.getPurchase(ITEM_SKU), mConsumeFinishedListener);
	                return;
	            }else if(gasPurchase2 != null && verifyDeveloperPayload(gasPurchase2)){
	            	 //Log.d(TAG, "We have gas. Consuming it.");
		                mHelper.consumeAsync(inventory.getPurchase(ITEM_SKU2), mConsumeFinishedListener);
		                return;
	            }
	            //Log.d(TAG, "Initial inventory query finished; enabling main UI.");
	            


	    }
	};
	IabHelper.OnConsumeFinishedListener mConsumeFinishedListener =
			  new IabHelper.OnConsumeFinishedListener() {

			@Override
			public void onConsumeFinished(Purchase purchase,
					IabResult result) {
				
				// if we were disposed of in the meantime, quit.
	            if (mHelper == null) return;
	            if (result.isSuccess()) {
	                //Log.d(TAG, "Consumption successful. Provisioning.");
	                isPurchased = true;
	                saveData();
	                alert("You are purchased, please restart app to apply");
				   	  btEnableReceiveVoiceMessage.setEnabled(true);
				   	  tvReceiveVoiceMessageTitle.setTextColor(Color.parseColor("#ffffff"));
				      textView3.setTextColor(Color.parseColor("#ffffff"));
				      btBuyFullVersion.setEnabled(false);
	            }
	            else {
	                complain("Error while consuming: " + result);
	            }
	            //Log.d(TAG, "End consumption flow.");
			}
		};
		private void setSharedPreferences(boolean settingsValue) {
			SharedPreferences settings = this.getSharedPreferences(
					Constant.LISTEN_ENABLED, 0);
			SharedPreferences.Editor editor = settings.edit();
			editor.putBoolean("silentMode", settingsValue);
			editor.commit();
		}
	@Override
	public void onDestroy() {
		super.onDestroy();
        // very important:
        //Log.d(TAG, "Destroying helper.");
        if (mHelper != null) {
            mHelper.dispose();
            mHelper = null;
        }
	}
	private void settingTabGeneral() {
		// tab general setting
		btRateApp = (Button) findViewById(R.id.btRateApp);
		radGroupTypeRecord = (RadioGroup) findViewById(R.id.radioGroupTypeRecord);
		radioGroupTypeReply = (RadioGroup) findViewById(R.id.radioGroupTypeReply);
		radReplySMS = (RadioButton) findViewById(R.id.radReplySMS);
		radReplyAudio = (RadioButton) findViewById(R.id.radReplyAudio);
		btEnableCall = (ToggleButton) findViewById(R.id.toggleEnableCall);
		btGeneralSetting = (Button) findViewById(R.id.btGeneralSetting);
		btBuyFullVersion = (Button) findViewById(R.id.btBuyFullVersion);
		btSelectContacts = (Button) findViewById(R.id.btSelectContact);
		btSyncToDropbox = (Button) findViewById(R.id.btSyncToDropbox);
		spDelayTimes = (Spinner) findViewById(R.id.spinner_delaytimes);
		toggleEnalbeAskBeforeDel = (ToggleButton) findViewById(R.id.toggleEnalbeAskBeforeDel);
		toggleEnalbeAskBeforeDelRR = (ToggleButton) findViewById(R.id.toggleEnalbeAskBeforeDelRe);
		btEnableReceiveVoiceMessage = (ToggleButton) findViewById(R.id.toggleEnableReceiveVoiceMessage);
		tvReceiveVoiceMessageTitle = (TextView) findViewById(R.id.tvReceiveVoiceMessageTitle);
		textView3 = (TextView) findViewById(R.id.tvSelectDelayTimeTitle);
		adViewSettingOne = (AdView) findViewById(R.id.adViewSettingOne);
		if(hasConnections() && isPurchased==false){
			Handler handler = new Handler();
			handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					AdRequest adRequest = new AdRequest.Builder().build();
					adViewSettingOne.loadAd(adRequest);
				}
			}, 10000); // Time > 10s.
			
		}else{
			adViewSettingOne.setVisibility(View.GONE);
		}
		String delayTimes[] = { "3 seconds", "4 seconds", "5 seconds",
				"6 seconds", "7 seconds", "8 seconds", "9 seconds",
				"10 seconds" };
		// Adapter
		ArrayAdapter<String> adapterdelayTimes;
		adapterdelayTimes = new ArrayAdapter<String>(this,
				R.layout.spinner_custom_text, delayTimes);
		spDelayTimes.setAdapter(adapterdelayTimes);
		btBuyFullVersion.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				buyClick(v);
			}
		});
	}

	private void settingTabContacts() {
		// tab Contacts
		tvNotes = (TextView) findViewById(R.id.tvContentSelect);
		radGroupTypeRecord = (RadioGroup) findViewById(R.id.radioGroupTypeRecord);
		radAllcalls = (RadioButton) findViewById(R.id.radAllcalls);
		radContacts = (RadioButton) findViewById(R.id.radContacts);
		radUnknown = (RadioButton) findViewById(R.id.radUnknown);
		lvContact = (ListView) findViewById(R.id.lvContact);
		adViewSettingTwo = (AdView) findViewById(R.id.adViewSettingTwo);
		if(hasConnections() && isPurchased==false){
			Handler handler = new Handler();
			handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					AdRequest adRequest = new AdRequest.Builder().build();
					adViewSettingTwo.loadAd(adRequest);
				}
			}, 10000); // Time > 10s.
			
		}else{
			adViewSettingTwo.setVisibility(View.GONE);
		}
	}

	private void settingTabSyncToDropbox() {
		// tab Sync to Dropbox
		toggleManual = (ToggleButton) findViewById(R.id.toggleManualSync);
		toggleAuto = (ToggleButton) findViewById(R.id.toggleAutoSync);
		btLink = (Button) findViewById(R.id.btLinkDropbox);
		btUnlink = (Button) findViewById(R.id.btUnlink);
		btRunCleanUp = (Button) findViewById(R.id.btRunCleanUp);
		adViewSettingThree = (AdView) findViewById(R.id.adViewSettingThree);
		if(hasConnections() && isPurchased==false){
			Handler handler = new Handler();
			handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					AdRequest adRequest = new AdRequest.Builder().build();
					adViewSettingThree.loadAd(adRequest);
				}
			}, 10000); // Time > 10s.
			
		}else{
			adViewSettingThree.setVisibility(View.GONE);
		}
		// Log.d("CONFIG", "Init Checked = "+cfg.get_value());
		if (mDropboxApi.getDbxAccountManager().hasLinkedAccount()) {
			btLink.setBackgroundResource(R.drawable.selector_synctab_btlink);
			btUnlink.setBackgroundResource(R.drawable.selector_synctab_btunlink);
		} else {
			btLink.setBackgroundResource(R.drawable.selector_synctab_btunlink);
			btUnlink.setBackgroundResource(R.drawable.selector_synctab_btlink);
		}
		if (cfgAutoSync.get_value() == 0) {
			toggleManual.setChecked(true);
			toggleAuto.setChecked(false);
		} else {

			toggleManual.setChecked(false);
			toggleAuto.setChecked(true);
		}
	}

	private void setEventClickButton() {
		btGeneralSetting.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				

				//Log.d("Tag", "Tab 0 click");
				if (positionTab != 0) {
					positionTab = 0;
					item_search.setVisible(false);
					isTabContact = 0;
					btSelectContacts
							.setBackgroundResource(R.drawable.selector_hometab_btdefault);
					btGeneralSetting
							.setBackgroundResource(R.drawable.selector_hometab_btselected);
					btSyncToDropbox
							.setBackgroundResource(R.drawable.selector_hometab_btdefault);
					mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(
							mContext, R.anim.in_from_left));
					mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(
							mContext, R.anim.out_to_right));
					mViewFlipper.setDisplayedChild(mViewFlipper
							.indexOfChild(findViewById(R.id.view_one)));

				}
			}
		});
		
		
		btSelectContacts.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				//Log.d("Tag", "Tab 1 click");
				if (positionTab != 1) {
					positionTab = 1;
					Log.d(TAG, "Contact tab is clicked !!! ");
					item_search.setVisible(true);
					isTabContact = 1;
					// Log.d("CONTACT",
					// "Contact adapter count = "+contactAdapter.getCount());
					lvContact.setAdapter(contactAdapter);

					cfgTypeRecord = dbHandler.getConfig(4);
					//Log.d("PHAM_VI_AP_DUNG", cfgTypeRecord.get_value() + "");

					if (cfgTypeRecord != null) {
						if (cfgTypeRecord.get_value() == 0) {
							radAllcalls.setChecked(true);
							tvNotes.setText("Select contact to Ignore");
						} else if (cfgTypeRecord.get_value() == 1) {
							tvNotes.setText("Select contact to Ignore");
							radContacts.setChecked(true);
						} else if (cfgTypeRecord.get_value() == 2) {
							tvNotes.setText("Select contact to Record");
							radUnknown.setChecked(true);
						}
					}

					btSelectContacts
							.setBackgroundResource(R.drawable.selector_hometab_btselected);
					btGeneralSetting
							.setBackgroundResource(R.drawable.selector_hometab_btdefault);
					btSyncToDropbox
							.setBackgroundResource(R.drawable.selector_hometab_btdefault);
					mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(
							mContext, R.anim.in_from_left));
					mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(
							mContext, R.anim.out_to_right));
					mViewFlipper.setDisplayedChild(mViewFlipper
							.indexOfChild(findViewById(R.id.view_two)));

				}
			}
		});
		btSyncToDropbox.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				//Log.d("Tag", "Tab 2 click");
				if (positionTab != 2) {
					positionTab = 2;
					item_search.setVisible(false);
					isTabContact = 0;
					btSelectContacts
							.setBackgroundResource(R.drawable.selector_hometab_btdefault);
					btGeneralSetting
							.setBackgroundResource(R.drawable.selector_hometab_btdefault);
					btSyncToDropbox
							.setBackgroundResource(R.drawable.selector_hometab_btselected);
					mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(
							mContext, R.anim.in_from_left));
					mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(
							mContext, R.anim.out_to_right));
					mViewFlipper.setDisplayedChild(mViewFlipper
							.indexOfChild(findViewById(R.id.view_three)));

				}
			}
		});
	}

	private void setEventClickButtonTabGeneral() {

		btRateApp.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				 Intent intent = new Intent(Intent.ACTION_VIEW);
				  String market_link = getPackageName();
				  intent.setData(Uri.parse("market://details?id="+market_link));
				  startActivity(intent);
			}
		});
		
		toggleEnalbeAskBeforeDel
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						
						if (isChecked) {
							cfgSmsDelete.set_value(0);
						} else {
							cfgSmsDelete.set_value(1);
						}
						dbHandler.updateConfig(cfgSmsDelete);
					}
				});
		toggleEnalbeAskBeforeDelRR
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						
						if (isChecked) {
							cfgRRDelete.set_value(0);
						} else {
							cfgRRDelete.set_value(1);
						}
						dbHandler.updateConfig(cfgRRDelete);
					}
				});

		btEnableCall.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
					
				if (isChecked) {
					cfg.set_value(1);
				} else {
					cfg.set_value(0);
				}
				dbHandler.updateConfig(cfg);	
				Intent intent = new Intent(mContext,WidgetIntentReceiver.class);
				intent.setAction("softtech.apps.intent.action.CHANGE_PICTURE");
				intent.putExtra("update",false);
				sendBroadcast(intent);
			}
		});
		radioGroupTypeReply
				.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						

						switch (checkedId) {
						case R.id.radReplySMS:
							cfgTypeReply.set_value(0);
							break;
						case R.id.radReplyAudio:
							cfgTypeReply.set_value(1);
							break;
						default:
							cfgTypeReply.set_value(0);
							break;
						}
						dbHandler.updateConfig(cfgTypeReply);
					}
				});
		btEnableReceiveVoiceMessage
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						
						if (isChecked) {
							cfgisreceivevoicemessage.set_value(1);
						} else {
							cfgisreceivevoicemessage.set_value(0);
						}
						dbHandler.updateConfig(cfgisreceivevoicemessage);
					}
				});
		spDelayTimes.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> adapter, View v,
					int position, long id) {
				// Showing selected spinner item
				//Log.d("DELAYTIME", "Item selected = " + position);
				// Update to database -> Select delay time
				switch (position) {
				case 0:
					cfgDelayTime.set_value(3);
					break;
				case 1:
					cfgDelayTime.set_value(4);
					break;
				case 2:
					cfgDelayTime.set_value(5);
					break;
				case 3:
					cfgDelayTime.set_value(6);
					break;
				case 4:
					cfgDelayTime.set_value(7);
					break;
				case 5:
					cfgDelayTime.set_value(8);
					break;
				case 6:
					cfgDelayTime.set_value(9);
					break;
				case 7:
					cfgDelayTime.set_value(10);
					break;
				default:
					cfgDelayTime.set_value(3);
					break;
				}
				dbHandler.updateConfig(cfgDelayTime);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				

			}
		});

	}

	private void setEventClickButtonTabContacts() {
		// page Contacts
		radGroupTypeRecord
				.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						

						switch (checkedId) {
						case R.id.radAllcalls:
							// update config
							cfgTypeRecord.set_value(0);
							dbHandler.updateConfig(cfgTypeRecord);

							// update UI
							tvNotes.setText("Select contact to Ignore");

							break;
						case R.id.radContacts:
							// update config
							cfgTypeRecord.set_value(1);
							dbHandler.updateConfig(cfgTypeRecord);

							// update UI
							tvNotes.setText("Select contact to Ignore");

							break;
						case R.id.radUnknown:
							// update config
							cfgTypeRecord.set_value(2);
							dbHandler.updateConfig(cfgTypeRecord);

							tvNotes.setText("Select contact to Record");

							break;
						default:
							cfgTypeRecord.set_value(0);
							dbHandler.updateConfig(cfgTypeRecord);
							break;
						}
						contactAdapter.notifyDataSetChanged();

						//Log.d("CHECKED",
						//		"Checked value = " + cfgTypeRecord.get_value());
						// cfgTypeRecord.set_value(newConf.get_value());
						lvContact.setAdapter(contactAdapter);
					}
				});

	}

	private void setEventClickButtonTabSyncToDropbox() {
		toggleManual.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				
				if (isChecked) {
					toggleAuto.setChecked(false);
					cfgAutoSync.set_value(0);
					dbHandler.updateConfig(cfgAutoSync);
					isSync = false;

				} else {
					toggleAuto.setChecked(true);
					cfgAutoSync.set_value(1);
					dbHandler.updateConfig(cfgAutoSync);
					if (!isSync) {
						isSync = true;

						autoSyncDropbox();
					}
				}

			}
		});

		toggleAuto.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				
				if (isChecked) {
					toggleManual.setChecked(false);
					cfgAutoSync.set_value(1);
					dbHandler.updateConfig(cfgAutoSync);
					if (!isSync) {
						isSync = true;

						autoSyncDropbox();
					}

				} else {
					toggleManual.setChecked(true);
					cfgAutoSync.set_value(0);
					dbHandler.updateConfig(cfgAutoSync);

					isSync = false;
				}
			}

		});

		// listener for RadioGroup Java Android example
		mRadioGroup = (RadioGroup) findViewById(R.id.radioGroupSync);

		radAllCalls = (RadioButton) findViewById(R.id.radButton_Allcalls);
		radFavorites = (RadioButton) findViewById(R.id.radButton_Favorites);
		//Log.d("CHECKED", "Init Radio checked = " + cfgTypeSync.get_value());
		if (cfgTypeSync.get_value() == 0) {
			radAllCalls.setChecked(true);
		} else {
			radFavorites.setChecked(true);
		}

		mRadioGroup
				.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						// Log.v("Selected", "New radio item selected: " +
						// checkedId);
						switch (checkedId) {
						case R.id.radButton_Allcalls:

							cfgTypeSync.set_value(0);
							dbHandler.updateConfig(cfgTypeSync);
							autoSyncDropbox();
							// do something
							break;

						case R.id.radButton_Favorites:
							cfgTypeSync.set_value(1);
							dbHandler.updateConfig(cfgTypeSync);
							autoSyncDropbox();
							// do something
							break;
						}
					}

				});

		// Run clean up button
		final AlertDialog.Builder builder = new AlertDialog.Builder(
				MainActivity.this);
		btRunCleanUp = (Button) findViewById(R.id.btRunCleanUp);
		btRunCleanUp.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				builder.setMessage(
						"This action clears all stored audio files (except for the backup file in dropbox account). Are you sure ?")
						.setNegativeButton("No", dialogCleanupClickListener)
						.setPositiveButton("Yes", dialogCleanupClickListener)
						.show();
			}
		});
		btLink.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				

				if (mDropboxApi == null) {
					mDropboxApi = new DropboxApi(mContext);
					mDropboxApi.registerAccountDropbox();

				}

				if (mDropboxApi.getDbxAccountManager() != null) {
					if (!mDropboxApi.getDbxAccountManager().hasLinkedAccount()) {
						mDropboxApi.getDbxAccountManager().startLink(
								MainActivity.this,
								REQUEST_LINK_TO_DBX_MAINACTIVITY);

					}
				}

				mDropboxApi.linkAccountToFileFS();

				Config configAutoSync = dbHandler
						.getConfigByKeyWord("synctodropbox");
				if (configAutoSync != null && configAutoSync.get_value() == 1) {
					isSync = true;

					autoSyncDropbox();

				} else {
					isSync = false;
				}
			}
		});

		btUnlink.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				

				btUnlink.setBackgroundResource(R.drawable.selector_synctab_btlink);

				btLink.setBackgroundResource(R.drawable.selector_synctab_btunlink);

				if (mDropboxApi != null) {
					if (mDropboxApi.getDbxAccountManager().hasLinkedAccount()) {

						mDropboxApi.getDbxAccountManager().unlink();

						mDropboxApi = null;

						isSync = false;

					}
				}
			}
		});

	}

	final DialogInterface.OnClickListener dialogCleanupClickListener = new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case DialogInterface.BUTTON_POSITIVE:
				// Yes
				String filepath = Environment.getExternalStorageDirectory()
						.getPath();
				File file = new File(filepath, FILE_DIRECTORY + "/"
						+ AUDIO_RECORDER_FOLDER_ALLCALLS);
				File file2 = new File(filepath, FILE_DIRECTORY + "/"
						+ AUDIO_RECORDER_FOLDER_FAVORITES);
				// Log.d("File", "File to delete = "+file.getAbsolutePath());
				deleteNon_EmptyDir(file);
				deleteNon_EmptyDir(file2);
				break;
			case DialogInterface.BUTTON_NEGATIVE:
				// No button clicked
				break;
			}
		}
	};

	public static boolean deleteNon_EmptyDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteNon_EmptyDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}
		return dir.delete();
	}

	private void showPage(int id) {
		actionBar.setDisplayHomeAsUpEnabled(true);

		viewFlipper.setInAnimation(AnimationUtils.loadAnimation(mContext,
				R.anim.in_from_right));

		viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(mContext,
				R.anim.out_to_left));

		viewFlipper.setDisplayedChild(viewFlipper
				.indexOfChild(findViewById(id)));

	}

	private void hideAllItemMenu(Menu menu) {
		for (int i = 0; i < menu.size(); i++)
			menu.getItem(i).setVisible(false);

	}

	@Override
	protected void onResume() {
		
		super.onResume();
		if (viewFlipper.getCurrentView().getId() == R.id.view_sms) {
			updateSms();
		} else if (viewFlipper.getCurrentView().getId() == R.id.view_record) {
			updateListRecord();
		} else if (viewFlipper.getCurrentView().getId() == R.id.view_listen) {
			updateListenVoice();
		}
		
		// Update config value
		if(btEnableCall != null){
			cfg = dbHandler.getConfig(1);
			int i = cfg.get_value();
			Log.d("RESUME", "On resume and set toggle value");
			if(i==1){
				// Update enable app button
				btEnableCall.setChecked(true);
			}else{
				btEnableCall.setChecked(false);
			}
		}
		autoSyncDropbox();
	}

	public void autoSyncDropbox() {

		if (dbHandler == null) {
			dbHandler = new DatabaseHandler(mContext);
		}

		Config configAutoSync = dbHandler.getConfigByKeyWord("synctodropbox");

		if (configAutoSync != null && configAutoSync.get_value() == 1) {
			// thuc hien chuc nang auto sync
			// kiem tra internet
			AsyncTask<String, Void, String> netWork = new AsyncTask<String, Void, String>() {

				@Override
				protected String doInBackground(String... urls) {
					String response = "";
					for (String url : urls) {
						try {
							HttpURLConnection urlc = (HttpURLConnection) (new URL(
									url).openConnection());
							urlc.setRequestProperty("User-Agent", "Test");
							urlc.setRequestProperty("Connection", "close");
							urlc.setConnectTimeout(1500);
							urlc.connect();
							response = String.valueOf(urlc.getResponseCode());
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					return response;
				}

				@Override
				protected void onPostExecute(String result) {
					if (result != null && result.length() > 0 && Integer.valueOf(result) == 200) {
						// do anything

						Config configSyncType = dbHandler
								.getConfigByKeyWord("syncrange");

						if (mDropboxApi == null) {
							mDropboxApi = new DropboxApi(mContext);
							mDropboxApi.registerAccountDropbox();

						}

						if (mDropboxApi.getDbxAccountManager() != null) {
							if (!mDropboxApi.getDbxAccountManager()
									.hasLinkedAccount()) {

								linkToDropbox = 0;

								AlertDialog.Builder builder = new AlertDialog.Builder(
										MainActivity.this);
								builder.setTitle("Dropbox login required !");

								builder.setMessage(
										"Please keep dropbox account login to auto-sync function can operate without interruption !\n\nChoose \"Login\" button to login otherwise choose \"Cancel\" button")
										.setPositiveButton(
												"Login",
												new DialogInterface.OnClickListener() {

													@Override
													public void onClick(
															DialogInterface dialog,
															int which) {
														mDropboxApi
																.getDbxAccountManager()
																.startLink(
																		MainActivity.this,
																		REQUEST_LINK_TO_DBX_MAINACTIVITY);
													}
												})
										.setNegativeButton(
												"Cancel",
												new DialogInterface.OnClickListener() {

													@Override
													public void onClick(
															DialogInterface dialog,
															int which) {

													}
												}).show();

							} else {
								mDropboxApi.linkAccountToFileFS();
								linkToDropbox = 1;
							}
						}

						if (configSyncType != null && linkToDropbox == 1) {

							// favorites
							File favorites = mDropboxApi.getFolderFavorites();
							File[] listFavorites = favorites.listFiles();
							for (File tmpFile : listFavorites) {
								// Log.e("TMP FILE", tmp.getAbsolutePath());
								if (tmpFile.isFile()
										&& tmpFile.getName().contains(
												Constant.ISSYNC0) && isSync) {

									mDropboxApi.syncFileToDropBoxFolder(1,
											tmpFile);
								}
							}

							if (configSyncType.get_value() == 0) {
								// all calls

								File allCalls = mDropboxApi.getFolderAllcall();
								File[] listAllCalls = allCalls.listFiles();
								for (File tmpFile : listAllCalls) {
									if (tmpFile.isFile()
											&& tmpFile.getName().contains(
													Constant.ISSYNC0) && isSync) {
										mDropboxApi.syncFileToDropBoxFolder(0,
												tmpFile);
									}
								}
							}

							adapterAllCalls.notifyDataSetChanged();
						} else {
							// default error config
						}
					}
				}

			};

			if (hasConnections()) {
				netWork.execute(new String[] { "http://www.google.com" });
			}
		} else {
			// sync by hand
		}
	}

	@Override
	public void onBackPressed() {
		
		if (viewFlipper.getCurrentView().getId() != R.id.view_main) {

			hideAllItemMenu(mMenu);

			actionBar.setTitle(R.string.app_name);

			actionBar.setDisplayHomeAsUpEnabled(false);

			actionBar
					.setBackgroundDrawable(new ColorDrawable(colorActionBarSMS));

			viewFlipper.setInAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.in_from_left));

			viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.out_to_right));

			viewFlipper.setDisplayedChild(viewFlipper
					.indexOfChild(findViewById(R.id.view_main)));
		} else {
			super.onBackPressed();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.

		getMenuInflater().inflate(R.menu.main, menu);

		mMenu = menu;
		hideAllItemMenu(mMenu);
		
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == android.R.id.home) {
			if (viewFlipper.getCurrentView().getId() != R.id.view_main) {

				onBackPressed();
			}
			return true;
		} else if (id == R.id.action_add_item_sms) {
			if (viewFlipper.getCurrentView().getId() == R.id.view_sms) {
				Intent intent = new Intent(mContext, DialogAddSms.class);
				intent.putExtra("requestCode", REQUEST_CODE_DIALOG_ADD_SMS);
				startActivityForResult(intent, REQUEST_CODE_DIALOG_ADD_SMS);
			} else if (viewFlipper.getCurrentView().getId() == R.id.view_schedule) {
				Intent intent = new Intent(mContext, AddSchedule.class);
				intent.putExtra("requestCode", REQUEST_CODE_ADD_SCHEDULE);
				startActivityForResult(intent, REQUEST_CODE_ADD_SCHEDULE);
			}
		} else if (id == R.id.action_add_item_record) {

			// start activity record
			// Intent intent = new Intent(mContext, DialogAddSms.class);
			// intent.putExtra("requestCode", REQUEST_CODE_DIALOG_ADD_RECORD);
			// startActivityForResult(intent, REQUEST_CODE_DIALOG_ADD_RECORD);
		} else if (id == R.id.action_sort_voice_recorde) {

			popup = new PopupMenu(mContext,
					findViewById(R.id.action_sort_voice_recorde));

			// This activity implements OnMenuItemClickListener
			popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {

				@Override
				public boolean onMenuItemClick(MenuItem item) {
					
					switch (item.getItemId()) {
					case R.id.action_sort_by_name:
						if (listRowVoiceRecorded != null) {
							Collections.sort(listRowVoiceRecorded,
									mSortRowVoiceRecorderByName);
							updateListenVoice();
						}
						break;
					case R.id.action_sort_by_time:
						if (listRowVoiceRecorded != null) {
							Collections.sort(listRowVoiceRecorded,
									mSortRowVoiceRecorderByTime);
							updateListenVoice();
						}
						break;
					default:
						if (listRowVoiceRecorded != null) {
							Collections.sort(listRowVoiceRecorded,
									mSortRowVoiceRecorderByTime);
							updateListenVoice();
						}
						break;
					}
					return false;
				}
			});
			MenuInflater inflater = popup.getMenuInflater();

			inflater.inflate(R.menu.actions, popup.getMenu());

			popup.show();
		}

		return super.onOptionsItemSelected(item);
	}

	/**
	 * checks if an external memory card is available
	 * 
	 * @return
	 */
	public static int updateExternalStorageState() {
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			return MEDIA_MOUNTED;
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			return MEDIA_MOUNTED_READ_ONLY;
		} else {
			return NO_MEDIA;
		}

	}

	/**
	 * Return the path of voice message to store
	 * 
	 * @param AUDIO_RECORDER_FOLDER
	 * */
	public String getFilename() {
		String filepath = Environment.getExternalStorageDirectory().getPath();
		folder = new File(filepath, FILE_DIRECTORY + "/"
				+ AUDIO_RECORDER_FOLDER);
		File file = folder;
		if (!file.exists()) {
			file.mkdirs();
		}
		// return (file.getAbsolutePath() + "/" + "Audio-Record-"
		// +System.currentTimeMillis() + file_exts[currentFormat]);
		return (file.getAbsolutePath() + "/" + "record-"
				+ System.currentTimeMillis() + "-.mp3");
		// + System.currentTimeMillis() +
	}

	/**
	 * Start recording a incoming call with input from
	 * MediaRecorder.AudioSource.MIC
	 * 
	 * @param recorder
	 * */
	public void startRecording() {
		/**
		 * Device audio manager
		 * */
		am = (AudioManager) getBaseContext().getSystemService(
				Context.AUDIO_SERVICE);
		am.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
				am.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL), 0);

		am.setMode(AudioManager.MODE_NORMAL);
		am.setSpeakerphoneOn(false);
		/**
		 * Recorder manager
		 * */
		recorder = new MediaRecorder();
		recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
		recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
		recorder.setMaxDuration(300000);

		path_record = getFilename();
		recorder.setOutputFile(path_record);
		recorder.setOnErrorListener(errorListener);
		recorder.setOnInfoListener(infoListener);

		/**
		 * Starting
		 * */
		try {
			recorder.prepare();
		} catch (IllegalStateException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		recorder.start();
		//Log.d("RECORD_INTENT", "Bat dau ghi am");

	}

	/**
	 * Stop a recorder and finish activity, add output file to wish list
	 * 
	 * @param recorder
	 * */
	public void stopRecording() {
		if (null != recorder) {
			//Log.d("RECORDING", "Stop recoding !!!! ");
			//Log.d("RECORDED", "File da record = " + path_record);
			recorder.stop();
			recorder.reset();
			recorder.release();
			recorder = null;
			mHandler.removeCallbacks(mUpdateTimeTask);
		}
	}

	private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
		@Override
		public void onError(MediaRecorder mr, int what, int extra) {
			// Toast.makeText(VoiceManagerActivity.this,
			// "Error: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
//			Log.e("ERROR", "Loi trong qua trinh ghi am ");
//			Log.e("ERROR", "Error: " + what + ", " + extra);
		}
	};

	private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
		@Override
		public void onInfo(MediaRecorder mr, int what, int extra) {
			// Toast.makeText(VoiceManagerActivity.this,
			// "Warning: " + what + ", " + extra, Toast.LENGTH_SHORT)
			// .show();
		}
	};

	private Runnable mUpdateTimeTask = new Runnable() {
		public void run() {
			final long start = mStartTime;
			long millis = SystemClock.uptimeMillis() - start;
			int seconds = (int) (millis / 1000);
			int minutes = seconds / 60;
			seconds = seconds % 60;
			String Phut = null;
			String Giay = null;
			if (minutes < 10) {
				Phut = "0" + minutes;
			} else {
				Phut = "" + minutes;
			}
			if (seconds < 10) {
				Giay = "0" + seconds;
			} else {
				Giay = "" + seconds;
			}
			tvTimeRecorded.setText(Phut + ":" + Giay);
			mHandler.postAtTime(this, start
					+ (((minutes * 60) + seconds + 1) * 1000));
		}
	};

	public void getContacts() {
		// Get all contact here
		ContentResolver cr = mContext.getContentResolver();
		Cursor cur = cr.query(
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
				null, null);
		cur.moveToFirst();

		while (cur.moveToNext()) {
			String contactId = cur.getString(cur
					.getColumnIndex(ContactsContract.Contacts._ID));

			// Log.e("contact id"," contact id="+contactId);

			String name = cur
					.getString(cur
							.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

			// String
			// phone=cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

			// Log.e("name","name="+name);

			String hasPhone = null;
			int hasphone = -1;
			try {
				hasPhone = cur
						.getString(cur
								.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
				hasphone = Integer.parseInt(hasPhone);
				// Log.e("contactID",contactId);
			} catch (Exception ex) {

				// Log.e("contactID",contactId);
			}
			if (hasphone > 0) {
				// Log.d("CONTACT", "Has phone number from SIM CARD");
				String phone = cur
						.getString(cur
								.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
				Contact ct = new Contact(contactId, name, phone, contactId, 0);
				listContact.add(ct);
			}
		}

	}

	private String getTimeString(long millis) {
		StringBuffer buf = new StringBuffer();

		int hours = (int) (millis / (1000 * 60 * 60));
		int minutes = (int) ((millis % (1000 * 60 * 60)) / (1000 * 60));
		int seconds = (int) (((millis % (1000 * 60 * 60)) % (1000 * 60)) / 1000);

		buf.append(String.format("%02d", hours)).append(":")
				.append(String.format("%02d", minutes)).append(":")
				.append(String.format("%02d", seconds));

		return buf.toString();
	}

	public void seekUpdation() {
		if (volumeControl != null && player != null) {
			volumeControl.setProgress(player.getCurrentPosition());
			seekHandler.postDelayed(run, 50);
		}

	}

	Runnable run = new Runnable() {

		@Override
		public void run() {
			seekUpdation();
		}
	};

	private void updateSms() {

		// update adapter
		if (adapterSms == null) {

			adapterSms = new ItemSmsAdapter(MainActivity.this);

		}

		adapterSms.updateListMessage();

		// update UI Sms
		updateSmsSub();
	}

	public void updateSmsSub() {
		if (dbHandler == null) {
			dbHandler = new DatabaseHandler(mContext);
		}

		Message msg = dbHandler.getMessageDefault();
		tvHeaderTitle.setText(msg.get_title());
		tvHeaderContent.setText(msg.get_content());
	}

	public void setRowDisplay(int position) {
		if (lvContent != null) {
			lvContent.requestFocusFromTouch();
			lvContent.setSelection(position);
		}
	}

	private void updateListRecord() {
		folder = new File(filepath, FILE_DIRECTORY + "/"
				+ AUDIO_RECORDER_FOLDER);
		files = folder.listFiles();
		list = new ArrayList<RowRecord>();
		for (File f : files) {
			if (f.getName().endsWith(".mp3") && f.getName().split("-").length > 2 && f.getName().split("-")[1].length() > 2) {
				// do something with them, add them to list or whatever
				list.add(new RowRecord(f.getName(), f.getAbsolutePath()));
			}
		}
		adapterRecord = new ItemRecordAdapter(mContext, list);

		lvRecord.setAdapter(adapterRecord);
	}

	private void updateListTimer(){
		
		if(dbHandler == null){
			dbHandler = new DatabaseHandler(mContext);
		}
		
		listTimer = dbHandler.getAllTimer();
		
		adapterTiming.updateListTimer(listTimer);
	}
	
	private void updateListenVoice() {
		if (adapterAllCalls == null) {
			adapterAllCalls = new ItemVoiceRecordAdapter(mContext,
					listRowVoiceRecorded);
		}

		adapterAllCalls.updateAdapter(listRowVoiceRecorded);
	}
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();

		// inflater.inflate(R.menu.dialog_record, menu);

		if (viewFlipper.getCurrentView().getId() == R.id.view_listen) {

			inflater.inflate(R.menu.dialog, menu);
		} else if (viewFlipper.getCurrentView().getId() == R.id.view_record) {
			inflater.inflate(R.menu.dialog_record, menu);
		}

	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// find out which menu item was pressed
		final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		RowRecord rowRecorded;

		//Log.d("CONTEXT", "on context item selected = " + info.position);
		switch (item.getItemId()) {
		case R.id.action_delete:
			//Log.d("SELECTED", "Delete");
			if (tabs.getCurrentTab() == 0) {
				adapterAllCalls = new ItemVoiceRecordAdapter(mContext,
						listRowVoiceRecorded);
				lvAllCalls.setAdapter(adapterAllCalls);
			} else {
				adapterAllCalls = new ItemVoiceRecordAdapter(mContext,
						listRowVoiceRecorded_favorites);
				lvFavorites.setAdapter(adapterAllCalls);
			}
			adapterAllCalls.removeItem(info.position);
			// Set update lai adapter -> public void
			// updateAdapter(List<RowVoiceRecorded> lst)
			return true;
		case R.id.action_backup:

			if (mDropboxApi != null
					&& !mDropboxApi.getDbxAccountManager().hasLinkedAccount()) {

				AlertDialog.Builder builder = new AlertDialog.Builder(
						MainActivity.this);
				builder.setTitle("Login Required !");
				builder.setMessage(
						"To use this feature requires you to sign in with your dropbox account.\n\n Choose \"Login\" button to Login or \"Cancel\" button to cancel !")
						.setNegativeButton("Cancel", dialogLoginClickListener)
						.setPositiveButton("Login", dialogLoginClickListener)
						.show();

			} else {
				Object object = adapterAllCalls.getItem(info.position);

				final RowVoiceRecorded rowVoiceRecorded = (RowVoiceRecorded) object;

				String pathString = rowVoiceRecorded.getmPath();

				if (pathString.contains(Constant.ISSYNC0)) {
					mDropboxApi.createFolderSofftech();

					mDropboxApi.linkAccountToFileFS();

					int type = -1;

					if (pathString.contains(Constant.FILE_ALLCALLS)) {

						type = 0;
					} else if (pathString.contains(Constant.FILE_FAVORITES)) {

						type = 1;
					}

					final File fileSync = new File(pathString);

					final int typeTmp = type;

					AsyncTask<String, Void, String> netWork = new AsyncTask<String, Void, String>() {

						@Override
						protected String doInBackground(String... urls) {
							String response = "";

							for (String url : urls) {
								try {
									HttpURLConnection urlc = (HttpURLConnection) (new URL(
											url).openConnection());
									urlc.setRequestProperty("User-Agent",
											"Test");
									urlc.setRequestProperty("Connection",
											"close");
									urlc.setConnectTimeout(1500);
									urlc.connect();
									response = String.valueOf(urlc
											.getResponseCode());
								} catch (Exception e) {
									e.printStackTrace();
								}
							}

							return response;
						}

						@Override
						protected void onPostExecute(String result) {
							if (result.length() > 0
									&& Integer.valueOf(result) == 200) {
								// do anything

								mDropboxApi.syncFileToDropBoxFolder(typeTmp,
										fileSync);

								View view = null;

								int position = -1;
								if (typeTmp == 0) {
									position = info.position
											- lvAllCalls
													.getFirstVisiblePosition();

									if (position <= 0) {
										position = lvAllCalls
												.getFirstVisiblePosition();
									}

									view = lvAllCalls.getChildAt(position);
								} else {
									position = info.position
											- lvFavorites
													.getFirstVisiblePosition();

									if (position <= 0) {
										position = lvFavorites
												.getFirstVisiblePosition();
									}

									view = lvFavorites.getChildAt(position);
								}

								if (view != null) {
									ImageView imgView = (ImageView) view
											.findViewById(R.id.imgCloud);

									imgView.setImageResource(R.drawable.ic_cloud_issync);
								}

								rowVoiceRecorded.setIsSync(true);

							} else {
								AlertDialog.Builder builder = new AlertDialog.Builder(
										MainActivity.this);
								builder.setTitle("Internet Connection Error !");
								builder.setMessage(
										"Please check for internet connection !")
										.setNegativeButton("Ok",
												dialogInternetClickListener)
										.show();
							}
						}

					};

					if (hasConnections()) {
						netWork.execute(new String[] { "http://www.google.com" });
					} else {
						AlertDialog.Builder builder = new AlertDialog.Builder(
								MainActivity.this);
						builder.setTitle("Internet Connection Error !");
						builder.setMessage(
								"Please check for internet connection !")
								.setNegativeButton("Ok",
										dialogInternetClickListener).show();
					}
				}
			}
			return true;
		case R.id.action_share:
			Log.d("SELECTED", "Share");
			Object a = adapterAllCalls.getItem(info.position);
			RowVoiceRecorded row = (RowVoiceRecorded) a;
			String file_path = row.getmPath();
			// Share this to social network
			Intent shareIntent = new Intent();
			shareIntent.setAction(Intent.ACTION_SEND);
			shareIntent.putExtra(Intent.EXTRA_TEXT, "http://softtech.vn");
			// Log.e(TAG , "phat file ="+PATH_APP +"/" + TEMP_FILE );
			shareIntent.putExtra(Intent.EXTRA_STREAM,
					Uri.fromFile(new File(file_path))); // doi cai path
			shareIntent.setType("audio/mp3"); // set lai cai type
			shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
			startActivity(Intent.createChooser(shareIntent, "Share with"));
			return true;
		case R.id.action_favorite:
			//Log.d("SELECTED", "Favorite");
			Object a2 = adapterAllCalls.getItem(info.position);
			RowVoiceRecorded row2 = (RowVoiceRecorded) a2;
			String file_path2 = row2.getmPath();
			String output = file_path2.replaceAll("/" + Constant.FILE_ALLCALLS
					+ "/", "/" + Constant.FILE_FAVORITES + "/");
			//Log.d("FILEPATH", "Duong dan file Path = " + file_path2);
			//Log.d("OUTPUT", "Duong dan output = " + output);
			boolean moved = Util.moveFile(file_path2, output);
			if (moved != true) {
				//Log.d("MOVED", "File has moved");
			} else {
				//Log.d("MOVED", "File hasn't moved yet !!");
			}
			return true;
		case R.id.action_edit_record:

			Intent intent = new Intent(mContext, DialogAddSms.class);

			intent.putExtra("requestCode",
					MainActivity.REQUEST_CODE_DIALOG_EDIT_RECORD);

			Object object = adapterRecord.getItem(info.position);

			rowRecorded = (RowRecord) object;

			if (rowRecorded != null) {

				if (rowRecorded.getmFileName().trim()
						.compareTo(ItemRecordAdapter.RECORD_DEFAULT) == 0) {
					AlertDialog.Builder builder = new AlertDialog.Builder(
							MainActivity.this);
					builder.setTitle("Warning !");
					builder.setMessage("Can not edit the default record app !")
							.setCancelable(false)
							.setPositiveButton("Ok",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
										}
									});
					Dialog aDialog = builder.create();
					aDialog.show();
				} else {
					intent.putExtra("pathRecord", rowRecorded.getmFilePath());

					startActivityForResult(intent,
							MainActivity.REQUEST_CODE_DIALOG_EDIT_RECORD);
				}
			}

			return true;
		case R.id.action_delete_record:

			object = adapterRecord.getItem(info.position);

			final RowRecord rRecorded = (RowRecord) object;

			if (rRecorded != null) {

				if (rRecorded.getmFileName().trim()
						.compareTo(ItemRecordAdapter.RECORD_DEFAULT) == 0) {
					AlertDialog.Builder builder = new AlertDialog.Builder(
							MainActivity.this);
					builder.setTitle("Warning!");
					builder.setMessage(
							"Can not delete the default record app !")
							.setCancelable(false)
							.setPositiveButton("Ok",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
										}
									});
					Dialog aDialog = builder.create();
					aDialog.show();
				} else {

					cfgRRDelete = dbHandler.getConfigByKeyWord("delrrcheck");

					View checkBoxView = View.inflate(mContext,
							R.layout.layout_radio_button, null);
					CheckBox checkBox = (CheckBox) checkBoxView
							.findViewById(R.id.checkBox);

					checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

						@Override
						public void onCheckedChanged(CompoundButton buttonView,
								boolean isChecked) {
							mIsCheck = isChecked;
						}
					});

					if (cfgRRDelete.get_value() == 0) {
						checkBox.setVisibility(View.VISIBLE);
					} else {
						checkBox.setVisibility(View.GONE);

						File file = new File(rRecorded.getmFilePath());
						if (file.exists()) {
							file.delete();
						}

						updateListRecord();
						return true;
					}

					AlertDialog.Builder builder = new AlertDialog.Builder(
							MainActivity.this);
					builder.setTitle("Warning!")
							.setView(checkBoxView)
							.setMessage(
									"The record will be deleted after this action !")
							.setCancelable(false)
							.setPositiveButton("DELETE",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {

											if (mIsCheck) {

												cfgRRDelete.set_value(1);

												dbHandler
														.updateConfig(cfgRRDelete);

												AlertDialog.Builder builder = new AlertDialog.Builder(
														MainActivity.this);
												builder.setTitle("Notice!");
												builder.setMessage(
														"To restore setting go to tab setting !")
														.setCancelable(true)
														.setPositiveButton(
																"Ok",
																new DialogInterface.OnClickListener() {
																	public void onClick(
																			DialogInterface dialog,
																			int id) {

																	}

																});

												Dialog aDialog = builder
														.create();
												aDialog.show();
											}

											File file = new File(rRecorded
													.getmFilePath());
											if (file.exists()) {
												file.delete();
											}
										}
									})
							.setNegativeButton("Cancel",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											

										}
									});
					Dialog aDialog = builder.create();
					aDialog.show();
				}
			}

			updateListRecord();
			return true;
		default:
			return false;
		}
	}

	private DialogInterface.OnClickListener dialogInternetClickListener = new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case DialogInterface.BUTTON_NEGATIVE:
				// No button clicked
				break;
			}
		}
	};

	private DialogInterface.OnClickListener dialogLoginClickListener = new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case DialogInterface.BUTTON_POSITIVE:
				// Yes
				mDropboxApi.getDbxAccountManager().startLink(MainActivity.this,
						REQUEST_LINK_TO_DBX_MAINACTIVITY);
				break;
			case DialogInterface.BUTTON_NEGATIVE:
				// No button clicked
				break;
			}
		}
	};

	public boolean hasConnections() {
		ConnectivityManager cm = (ConnectivityManager) mContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		if (null == ni)
			return false;
		return ni.isConnectedOrConnecting();
	}
	
	// Ads Zone for Free Version
	private final Handler handle1 =new Handler(){

		@Override
		public void handleMessage(android.os.Message msg) {
			
			Bundle b=msg.getData();
			Boolean dieukien=b.getBoolean("showMe");
			if(dieukien){
				// Code buoc 1
				if(hasConnections()){
					// Load add full screen here
					// Create the interstitial.
					interstitial = new InterstitialAd(getApplicationContext());
					AdRequest ads = new AdRequest.Builder().build();
					interstitial.setAdUnitId("ca-app-pub-2100208056165316/9348312789");
					interstitial.loadAd(ads);
					interstitial.setAdListener(new AdListener() {

						@Override
						public void onAdClosed() {
							
							super.onAdClosed();
							//test handler
							android.os.Message msg=new android.os.Message();
							Bundle b=new Bundle();
							b.putBoolean("showMe", true);
							msg.setData(b);
							handle1.sendMessage(msg);
						}
					});
					Handler handler = new Handler();
					handler.postDelayed(new Runnable() {
					    @Override
					    public void run() {
					    	displayInterstitial();
					    }
					}, mDelayTime); // Time > 10s.
					}
			}
		}
		
	};
	public void displayInterstitial() {
		mDelayTime = 300000 ;
		if (interstitial.isLoaded()) {
			
			// show quang cao
			interstitial.show();

		} else {
		}
	}
    @Override
	protected void onPause() {
		
		super.onPause();
		//test handler
		android.os.Message msg=new android.os.Message();
		Bundle b=new Bundle();
		b.putBoolean("showMe", false);
		msg.setData(b);
		handle1.sendMessage(msg);
	}

	boolean verifyDeveloperPayload(Purchase p) {
        String payload = p.getDeveloperPayload();
        
        /*
         * TODO: verify that the developer payload of the purchase is correct. It will be
         * the same one that you sent when initiating the purchase.
         * 
         * WARNING: Locally generating a random string when starting a purchase and 
         * verifying it here might seem like a good approach, but this will fail in the 
         * case where the user purchases an item on one device and then uses your app on 
         * a different device, because on the other device you will not have access to the
         * random string you originally generated.
         *
         * So a good developer payload has these characteristics:
         * 
         * 1. If two different users purchase an item, the payload is different between them,
         *    so that one user's purchase can't be replayed to another user.
         * 
         * 2. The payload must be such that you can verify it even when the app wasn't the
         *    one who initiated the purchase flow (so that items purchased by the user on 
         *    one device work on other devices owned by the user).
         * 
         * Using your own server to store and verify developer payloads across app
         * installations is recommended.
         */
        
        return true;
    }

    void saveData() {

        /*
         * WARNING: on a real application, we recommend you save data in a secure way to
         * prevent tampering. For simplicity in this sample, we simply store the data using a
         * SharedPreferences.
         */

        SharedPreferences.Editor spe = getPreferences(MODE_PRIVATE).edit();
        spe.putBoolean("isPurchased", true);
        spe.commit();
        //Log.d(TAG, "Saved data: tank = " + String.valueOf(isPurchased));
    }

    void loadData() {
        SharedPreferences sp = getPreferences(MODE_PRIVATE);
        isPurchased = sp.getBoolean("isPurchased", false);
        //Log.d(TAG, "Loaded data: Purchase = " + String.valueOf(isPurchased));
    }
    void complain(String message) {
        //Log.e(TAG, "**** TrivialDrive Error: " + message);
        alert("Error: " + message);
    }

    void alertMessage(String message) {
        AlertDialog.Builder bld = new AlertDialog.Builder(this);
        bld.setMessage(message);
        bld.setNeutralButton("OK", null);
        //Log.d(TAG, "Showing alert dialog: " + message);
        bld.create().show();
    }
    
    /**
     * init purchaed
     */
    void initPurchased(){
    	String base64EncodedPublicKey = 
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAi30rOlg2GETmorQfs0xY1hz0hQWgL94C2NNo+uAk1Lf+lNQoTS8BNW6LatOwd/Zs1TU8lAPIvRfsjiGqy00aY7WxeT1YoGkGBcBfwqj5y1E/Qa0H8b1RHHQGHXjgglNQJqU4jFULtHU23uygQzbVJv+B7KJfK26HJBySF23iQEM6fyj6oqHzCGlOJ65jih195+sBNEg5cX+T2ayjky9/nqb42DwWEIU/VdWXIXvoVvHjhqIaXQCWpjI/jkqeR1VGcXtPcBuEcPFcok/9AL46YdG6PtwiKI7hN/6Z752VoGTb1u1B6IA6PZyWJM77Yo9Kx9Li4+wLRE4zusbk2/BohQIDAQAB";
    	mHelper = new IabHelper(MainActivity.this, base64EncodedPublicKey);
		mHelper.enableDebugLogging(true);
		mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {

			@Override
			public void onIabSetupFinished(IabResult result) {
				
				if (!result.isSuccess()) {
					complain("Problem setting up in-app billing: " + result);
                    return;
				}
				if (mHelper == null) return;
                if(isPurchased==true){
                	//complain("This product has purchased");
                }else{
                	complain("This product hasn't purchased yet, buy full version to use full feature");
                	// Check has connection yet?
                	/*
                	if(hasConnections()){
                		// Do some thing here
                		// IAB is fully set up. Now, let's get an inventory of stuff we own.
                       //Log.d(TAG, "Setup successful. Querying inventory.");
                       // mHelper.queryInventoryAsync(false,mGotInventoryListener);
                        final List<String> skuList = new ArrayList<String>();
                        skuList.add(ITEM_SKU);
                        if (skuList != null) {
                            if (skuList.size() > 0) {
                                try {
                                	//complain("Co ket noi, thu request !!");
                                    mHelper.queryInventoryAsync(true, skuList, mGotInventoryListener);
                                } catch (Exception e) { 
                                    //e.printStackTrace();
                                }
                            }
                        }
                	}*/
                }
			}
		});
    }
    
}
